﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Henke.DevUI.Controls.Behaviors.ShowHide
{
    /// <summary>
    /// Adds a contextmenu to the datagrid that shows/hides columns
    /// </summary>
    public class ShowHideColumns : Behavior<DataGrid>
    {

        protected override void OnAttached()
        {
            base.OnAttached();
            AssociatedObject.Loaded += OnLoad;
        }

        private void OnLoad(object sender, RoutedEventArgs e)
        {
            var contextMenu = AssociatedObject.ContextMenu ?? new ContextMenu();
            foreach (var dataGridColumn in AssociatedObject.Columns)
            {
                if (GetInclude(dataGridColumn))
                    contextMenu.Items.Add(new MenuItem { Command = new ToggleColumnVisibilityCommand(dataGridColumn), Header = dataGridColumn.Header });
            }
            AssociatedObject.ContextMenu = contextMenu;
            AssociatedObject.Loaded -= OnLoad;
        }

        public static bool GetInclude(DataGridColumn obj)
        {
            return (bool)obj.GetValue(IncludeProperty);
        }

        public static void SetInclude(DataGridColumn obj, bool value)
        {
            obj.SetValue(IncludeProperty, value);
        }

        public static readonly DependencyProperty IncludeProperty =
            DependencyProperty.RegisterAttached("Include", typeof(bool), typeof(ShowHideOnCommandBehavior), new UIPropertyMetadata(true));
    }
}
